package handler

import (
	"admin-ease/global"
	"admin-ease/internal/dto"
	"admin-ease/internal/model"
	"encoding/json"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type UserHandel struct {
}

func NewUserHandel() *UserHandel {
	return &UserHandel{}
}
func (u *UserHandel) Regis(c *gin.Context) {
	var req dto.UserReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, dto.UserResp{
			Msg:  "参数获取失败",
			Code: 500,
		})
		return
	}
	user := model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}
	err = global.DB.Debug().Create(&user).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, dto.UserResp{
			Msg:  "注册失败",
			Code: 500,
		})
		return
	}
	c.JSON(http.StatusOK, dto.UserResp{
		Msg:  "注册成功",
		Code: 200,
		Data: user.ID,
	})
	return
}
func (u *UserHandel) UserList(c *gin.Context) {
	result, _ := global.Rdb.Get(global.Ctx, "userList").Result()
	if result == "" {
		var user []model.User
		err := global.DB.Debug().Find(&user).Error
		if err != nil {
			c.JSON(http.StatusBadRequest, dto.UserResp{
				Msg:  "列表查询失败",
				Code: 500,
			})
			return
		}
		marshal, _ := json.Marshal(user)
		global.Rdb.Set(global.Ctx, "userList", marshal, time.Hour*24)
		c.JSON(http.StatusOK, dto.UserResp{
			Msg:  "列表查询成功",
			Code: 200,
			Data: user,
		})
		return
	} else {
		json.Unmarshal([]byte{}, &result)
		c.JSON(http.StatusOK, dto.UserResp{
			Msg:  "列表查询成功",
			Code: 200,
			Data: result,
		})
		return
	}

}
